<!-- 物资设备采购策划表 -->
<template>
  <div>
    <a-card>
      <title-name title="物资设备采购策划表" />
      <div
        class="mb20"
        v-if="queryInfo.pageType !== 'detail'"
      >
        <ExcelImportButton
          ref="excelImportButton"
          :loading="importLoading"
          icon="import"
          button-text="批量导入"
          v-if=" hideBuquBtn()"
          @handleSubmit="handleImport"
        />
        <ExportMould
          v-if="hideBuquBtn()"
          class="ml20"
          button-text="下载导入模板"
          template-code="物资设备采购策划表.xlsx"
          icon="cloud-download"
        />
      </div>
      <a-table
        :columns="columns"
        :data-source="data"
        bordered
        :scroll="{ x: 3950 }"
        :pagination="false"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <!-- 物资名称 -->
        <span
          slot="name"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-name'"
            :text="text"
            @change="onCellChange(record, 'name', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>
        <!-- 采购方式 -->
        <span
          slot="procurementMethod"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-procurementMethod'"
            :text="text"
            @change="onCellChange(record, 'procurementMethod', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>
        <!-- 责任人及计划时间 -->
        <span
          slot="responsibleTime"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-responsibleTime'"
            :text="text"
            @change="onCellChange(record, 'responsibleTime', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>
        <!-- 产运周期（天） -->
        <span
          slot="productionCycle"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :required="true"
            v-else
            :key="index + '-productionCycle'"
            :text="text"
            @change="onCellChange(record, 'productionCycle', $event)"
          ></EditableNumber>
        </span>
        <!-- 最迟时间 -->
        <template
          slot="materialLatestTime"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableDate
            :required="true"
            v-else
            :key="index + '-materialLatestTime'"
            :text="text"
            @change="onCellChange(record, 'materialLatestTime', $event)"
          ></EditableDate>
        </template>
        <!-- 责任人 -->
        <span
          slot="materialResponsibleId"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ record.materialResponsibleName }}</span>
          <div
            v-else
            class="requiredFormItem"
          >
            <SelectPerson
              :fetching="fetching"
              :key="index + '-materialResponsibleId'"
              @changeEmployeeName="changeEmployeeName"
              :memberList="memberList"
              :record="record"
              bindKey="materialResponsibleId"
            ></SelectPerson>
          </div>
        </span>

        <!-- 最迟时间 -->
        <template
          slot="tenderLatestTime"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableDate
            :required="true"
            v-else
            :key="index + '-tenderLatestTime'"
            :text="text"
            @change="onCellChange(record, 'tenderLatestTime', $event)"
          ></EditableDate>
        </template>
        <!-- 责任人 -->
        <span
          slot="tenderResponsibleId"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ record.tenderResponsibleName }}</span>
          <div
            v-else
            class="requiredFormItem"
          >
            <SelectPerson
              :fetching="fetching"
              :key="index + '-tenderResponsibleId'"
              @changeEmployeeName="changeEmployeeName"
              :memberList="memberList"
              :record="record"
              bindKey="tenderResponsibleId"
            ></SelectPerson>
          </div>
        </span>

        <!-- 最迟时间 -->
        <template
          slot="brandLatestTime"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableDate
            :required="true"
            v-else
            :key="index + '-brandLatestTime'"
            :text="text"
            @change="onCellChange(record, 'brandLatestTime', $event)"
          ></EditableDate>
        </template>
        <!-- 责任人 -->
        <span
          slot="brandResponsibleId"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ record.brandResponsibleName }}</span>
          <div
            v-else
            class="requiredFormItem"
          >
            <SelectPerson
              :fetching="fetching"
              :key="index + '-brandResponsibleId'"
              @changeEmployeeName="changeEmployeeName"
              :memberList="memberList"
              :record="record"
              bindKey="brandResponsibleId"
            ></SelectPerson>
          </div>
        </span>

        <!-- 最迟时间 -->
        <template
          slot="demandLatestTime"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableDate
            :required="true"
            v-else
            :key="index + '-demandLatestTime'"
            :text="text"
            @change="onCellChange(record, 'demandLatestTime', $event)"
          ></EditableDate>
        </template>
        <!-- 责任人 -->
        <span
          slot="demandResponsibleId"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ record.demandResponsibleName }}</span>
          <div
            v-else
            class="requiredFormItem"
          >
            <SelectPerson
              :fetching="fetching"
              :key="index + '-demandResponsibleId'"
              @changeEmployeeName="changeEmployeeName"
              :memberList="memberList"
              :record="record"
              bindKey="demandResponsibleId"
            ></SelectPerson>
          </div>
        </span>

        <!-- 风险源分析 -->
        <span
          slot="riskSourceAnalysis"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-riskSourceAnalysis'"
            :text="text"
            @change="onCellChange(record, 'riskSourceAnalysis', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>

        <!-- 风险辨识 -->
        <span
          slot="riskIdentification"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-riskIdentification'"
            :text="text"
            @change="onCellChange(record, 'riskIdentification', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>

        <!-- 应对措施 -->
        <span
          slot="solutions"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            :required="true"
            v-else
            :key="index + '-solutions'"
            :text="text"
            @change="onCellChange(record, 'solutions', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>

        <!-- 甲方认定价格 -->
        <span
          slot="partyARecognizePrice"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-partyARecognizePrice'"
            :text="text"
            @change="onCellChange(record, 'partyARecognizePrice', $event)"
          ></EditableNumber>
        </span>

        <!-- 成本 -->
        <span
          slot="cost"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-cost'"
            :text="text"
            @change="onCellChange(record, 'cost', $event)"
          ></EditableNumber>
        </span>

        <!-- 价差效益(元) -->
        <span
          slot="spreadsBenefit"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-spreadsBenefit'"
            :text="text"
            @change="onCellChange(record, 'spreadsBenefit', $event)"
          ></EditableNumber>
        </span>

        <!-- 量差效益(元)-->
        <span
          slot="amountBenefit"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-amountBenefit'"
            :text="text"
            @change="onCellChange(record, 'amountBenefit', $event)"
          ></EditableNumber>
        </span>

        <!-- 效益总额(元) -->
        <span
          slot="totalBenefit"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-totalBenefit'"
            :text="text"
            @change="onCellChange(record, 'totalBenefit', $event)"
          ></EditableNumber>
        </span>

        <!-- 效益率 -->
        <span
          slot="benefitRate"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableNumber
            :min="-Infinity"
            :precision="2"
            :required="true"
            v-else
            :step="0.01"
            :key="index + '-benefitRate'"
            :text="text"
            @change="onCellChange(record, 'benefitRate', $event)"
          ></EditableNumber>
        </span>

        <!-- 备注 -->
        <span
          slot="remark"
          slot-scope="text, record, index"
        >
          <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
          <EditableCell
            v-else
            :key="index + '-remark'"
            :text="text"
            @change="onCellChange(record, 'remark', $event)"
            :maxLength="300"
          ></EditableCell>
        </span>

        <span
          slot="operation"
          slot-scope="text, record"
        >
          <template>
            <a-popconfirm
              title="请确认是否要删除？"
              @confirm="() => onDelete(record)"
            >
              <a href="javascript:;">删除</a>
            </a-popconfirm>
          </template>
        </span>
      </a-table>
      <a-button
        class="mt20"
        type="primary"
        @click="addRow"
        v-if="queryInfo.pageType !== 'detail'"
      > 增行 </a-button>
    </a-card>
  </div>
</template>

<script>
import { queryPlanSubSelectDetail } from '@/api/projectManagementPlanning/projectPlanningTaskList'
import EditableCell from '../../projectPlanningTaskList/detail/components/EditableCell'
import EditableNumber from '../../projectPlanningTaskList/detail/components/EditableNumber'
import EditableDate from '../../projectPlanningTaskList/detail/components/EditableDate'
import { getOrganizeUserListQuick } from '@/api/commons'
import ExportMould from '@/components/ExportMould'
import SelectPerson from './ProjectDesignPlanningForm/SelectPerson'
import { planMaterialupdateByPrimaryKeySelective } from '@/api/projectManagementPlanning/projectPlanningTaskList'

const DEFAULT_ROW = [
  {
    name: '',
    procurementMethod: '',
    responsibleTime: '',
    productionCycle: '',
    materialLatestTime: '',
    materialResponsibleId: undefined,
    tenderLatestTime: '',
    tenderResponsibleId: undefined,
    brandLatestTime: '',
    brandResponsibleId: undefined,
    demandLatestTime: '',
    demandResponsibleId: undefined,
    riskSourceAnalysis: '',
    solutions: '',
    partyARecognizePrice: '',
    riskIdentification: '',
    cost: '', // 成本
    spreadsBenefit: '',
    amountBenefit: '',
    totalBenefit: '',
    benefitRate: '',
    remark: '',
    guid: new Date().getTime()
  }
]

const REQUEST_KEYS = [
  'name',
  'procurementMethod',
  'responsibleTime',
  'productionCycle',
  'materialLatestTime',
  'materialResponsibleId',
  'tenderLatestTime',
  'tenderResponsibleId',
  'brandLatestTime',
  'brandResponsibleId',
  'demandLatestTime',
  'demandResponsibleId',
  'riskSourceAnalysis',
  'riskIdentification',
  'solutions',
  'partyARecognizePrice',
  'cost',
  'spreadsBenefit',
  'amountBenefit',
  'totalBenefit',
  'benefitRate'
]
export default {
  name: 'ProcurementPlanning',
  data() {
    return {
      queryInfo: {
        id: '',
        pageType: ''
      },
      columns: [
        {
          title: '序号',
          width: 50,
          align: 'center',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '物资名称',
          width: 150,
          align: 'center',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '工作计划',
          align: 'center',
          children: [
            {
              title: '采购方式',
              width: 100,
              align: 'center',
              dataIndex: 'procurementMethod',
              scopedSlots: { customRender: 'procurementMethod' }
            },
            {
              title: '责任人及计划时间',
              width: 200,
              align: 'center',
              dataIndex: 'responsibleTime',
              scopedSlots: { customRender: 'responsibleTime' }
            },
            {
              title: '产运周期(天)',
              width: 150,
              align: 'center',
              dataIndex: 'productionCycle',
              scopedSlots: { customRender: 'productionCycle' }
            },
            {
              title: '物资进场',
              align: 'center',
              children: [
                {
                  title: '最迟时间',
                  width: 180,
                  align: 'center',
                  dataIndex: 'materialLatestTime',
                  scopedSlots: { customRender: 'materialLatestTime' }
                },
                {
                  title: '责任人',
                  width: 220,
                  align: 'center',
                  dataIndex: 'materialResponsibleId',
                  scopedSlots: { customRender: 'materialResponsibleId' }
                }
              ]
            },
            {
              title: '物资招标',
              align: 'center',
              children: [
                {
                  title: '最迟时间',
                  width: 180,
                  align: 'center',
                  dataIndex: 'tenderLatestTime',
                  scopedSlots: { customRender: 'tenderLatestTime' }
                },
                {
                  title: '责任人',
                  width: 220,
                  align: 'center',
                  dataIndex: 'tenderResponsibleId',
                  scopedSlots: { customRender: 'tenderResponsibleId' }
                }
              ]
            },
            {
              title: '品牌业主确认',
              align: 'center',
              children: [
                {
                  title: '最迟时间',
                  width: 180,
                  align: 'center',
                  dataIndex: 'brandLatestTime',
                  scopedSlots: { customRender: 'brandLatestTime' }
                },
                {
                  title: '责任人',
                  width: 220,
                  align: 'center',
                  dataIndex: 'brandResponsibleId',
                  scopedSlots: { customRender: 'brandResponsibleId' }
                }
              ]
            },
            {
              title: '需求计划编制',
              align: 'center',
              children: [
                {
                  title: '最迟时间',
                  width: 180,
                  align: 'center',
                  dataIndex: 'demandLatestTime',
                  scopedSlots: { customRender: 'demandLatestTime' }
                },
                {
                  title: '责任人',
                  width: 220,
                  align: 'center',
                  dataIndex: 'demandResponsibleId',
                  scopedSlots: { customRender: 'demandResponsibleId' }
                }
              ]
            }
          ]
        },
        {
          title: '风险源分析',
          width: 150,
          align: 'center',
          dataIndex: 'riskSourceAnalysis',
          scopedSlots: { customRender: 'riskSourceAnalysis' }
        },
        {
          title: '风险辨识',
          width: 200,
          align: 'center',
          dataIndex: 'riskIdentification',
          scopedSlots: { customRender: 'riskIdentification' }
        },
        {
          title: '应对措施',
          align: 'center',
          dataIndex: 'solutions',
          width: 200,
          scopedSlots: { customRender: 'solutions' }
        },
        {
          title: '甲方认价(元)',
          width: 150,
          // width: 72,
          align: 'center',
          dataIndex: 'partyARecognizePrice',
          scopedSlots: { customRender: 'partyARecognizePrice' }
        },
        {
          title: '成本(元)',
          width: 150,
          align: 'center',
          dataIndex: 'cost',
          scopedSlots: { customRender: 'cost' }
        },
        {
          title: '价差效益(元)',
          width: 150,
          align: 'center',
          dataIndex: 'spreadsBenefit',
          scopedSlots: { customRender: 'spreadsBenefit' }
        },
        {
          title: '量差效益(元)',
          width: 150,
          align: 'center',
          dataIndex: 'amountBenefit',
          scopedSlots: { customRender: 'amountBenefit' }
        },
        {
          title: '效益总额(元)',
          width: 150,
          align: 'center',
          dataIndex: 'totalBenefit',
          scopedSlots: { customRender: 'totalBenefit' }
        },
        {
          title: '效益率(%)',
          width: 150,
          align: 'center',
          dataIndex: 'benefitRate',
          scopedSlots: { customRender: 'benefitRate' }
        },
        {
          title: '备注',
          width: 150,
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' }
        },
        {
          title: '操作',
          align: 'center',
          fixed: 'right',
          width: 100,
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [],
      memberList: [], // 接收人
      fetching: false,
      // 导入中
      importLoading: false
    }
  },

  props: {
    spinning: Boolean,
    baseFormInfo: {
      type: Object,
      default: () => {}
    }
  },

  components: { EditableCell, EditableNumber, EditableDate, SelectPerson, ExportMould },

  computed: {},

  watch: {
    baseFormInfo: {
      handler(val) {
        if (val.projectId) {
          this.getImplees()
        }
      },
      immediate: true
    }
  },

  created() {
    const { id, pageType, version = '' } = this.$route.query
    /**
     * version 不存在 就是正常入口进来的。
     * 否则 就是在V1等弹窗进来的
     */
    this.queryInfo.id = id
    this.queryInfo.pageType = pageType
    this.queryInfo.version = version
    if (this.queryInfo.pageType === 'detail') {
      this.columns.pop()
    }
    this.queryPlanSubSelectDetail()
  },

  mounted() {},

  methods: {
    // 增行
    addRow() {
      const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
      this.data.push({ ...[...DEFAULT_ROW_][0], guid: this.getGuid() })
    },
    // 草稿
    ProcurementPlanningSaveDrafts(formBase) {
      this.$emit('update:spinning', true)
      const query = {
        list: JSON.parse(JSON.stringify(this.data)),
        changed: this.queryInfo.pageType === 'change' ? true : false,
        planTaskDetailId: this.queryInfo.id,
        statusEnum: 'DRAFT',
        version: this.queryInfo.version
      }
      planMaterialupdateByPrimaryKeySelective(query)
        .then((res) => {
          this.$emit('update:spinning', false)
          this.$message.success('保存成功')
        })
        .catch(() => {
          this.$emit('update:spinning', false)
        })
    },
    /**
     * @description: 表格数字列校验
     * @param {array} list 表格数据
     * @param {array} fields 需要校验的字段
     * @return {object} {pass:boolean,text:string}
     */     
    numberValidate(list,fields){
      let result = {
        pass: true,
        text: '如下字段数据校验不通过！'
      }
      for(let i = 0; i < list.length; i ++){
        let row = ''
        for(let j = 0; j < fields.length; j ++){
          switch(fields[j].type){
            case 'number':
              if(typeof list[i][fields[j].key] !== 'number'){
                result.pass = false
                row += row === '' ? `第${i+1}行：${fields[j].title}` : `、${fields[j].title}`
              }
              break
            case 'date':
              if(this.moment(list[i][fields[j].key])._i === 'Invalid date'){
                result.pass = false
                row += row === '' ? `第${i+1}行：${fields[j].title}` : `、${fields[j].title}`
              }
              break

          }
          if(j===fields.length-1){
            result.text += row
          }
        }
      }
      result.text += ' 请更正后提交'
      return result
    },
    // 提交
    ProcurementPlanningSubmit(formBase) {
      let flag = true // 是否全部填写
      this.data.map((v) => {
        REQUEST_KEYS.map((k) => {
          if (v[k] === '' || v[k] == null || v[k] == undefined || (v[k] + '').replace(/\s*/g, '') == '') {
            flag = false
          }
        })
      })
      if (this.data.length === 0) {
        this.$warning({
          title: '提示',
          content: '请至少填写一行数据',
          okText: '确定'
        })
        return
      }
      if (!flag) {
        this.$warning({
          title: '提示',
          content: '请将数据填写完整',
          okText: '确定'
        })
        return
      } else {
        const {pass,text} = this.numberValidate(this.data,[
          {
            key: 'productionCycle',
            title: '工作计划-产运周期(天)',
            type: 'number'
          },
          {
            key: 'materialLatestTime',
            title: '工作计划-物资进场-最迟时间',
            type: 'date'
          },
          {
            key: 'tenderLatestTime',
            title: '工作计划-物资招标-最迟时间',
            type: 'date'
          },
          {
            key: 'brandLatestTime',
            title: '工作计划-品牌业主确认-最迟时间',
            type: 'date'
          },
          {
            key: 'demandLatestTime',
            title: '工作计划-需求计划编制-最迟时间',
            type: 'date'
          },
          {
            key: 'partyARecognizePrice',
            title: '甲方认价(元)',
            type: 'number'
          },
          {
            key: 'cost',
            title: '成本(元)',
            type: 'number'
          },
          {
            key: 'spreadsBenefit',
            title: '价差效益(元)',
            type: 'number'
          },
          {
            key: 'amountBenefit',
            title: '量差效益(元)',
            type: 'number'
          },
          {
            key: 'totalBenefit',
            title: '效益总额(元)',
            type: 'number'
          }
        ])
        if(!pass){
          this.$message.warning(text)
          return
        }
        this.$confirm({
          title: '提交',
          content: '请确认是否要提交？',
          onOk: async () => {
            this.$emit('update:spinning', true)
            const query = {
              list: JSON.parse(JSON.stringify(this.data)),
              changed: this.queryInfo.pageType === 'change' ? true : false,
              planTaskDetailId: this.queryInfo.id,
              statusEnum: 'SUBMITTED',
              version: this.queryInfo.version
            }
            planMaterialupdateByPrimaryKeySelective(query)
              .then((res) => {
                this.$emit('update:spinning', false)
                this.$message.success('提交成功')
                this.$close()
              })
              .catch(() => {
                this.$emit('update:spinning', false)
              })
          }
        })
      }
    },
    getGuid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0
        var v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    },
    // 删除item
    onDelete(item) {
      let arr = JSON.parse(JSON.stringify(this.data))
      arr = arr
        .map((v) => {
          if (v.guid !== item.guid) {
            return v
          }
        })
        .filter((v) => v && v.guid)
      this.data = arr
    },
    // 更新item
    onCellChange(item, dataIndex, value) {
      this.data.map((v) => {
        if (v.guid === item.guid) {
          v[dataIndex] = value
        }
      })
    },
    // 获取接收人
    getImplees() {
      this.fetching = true
      getOrganizeUserListQuick({ projectId: this.baseFormInfo.projectId }).then((res) => {
        const obj = {}
        // 去掉重复以及employeeId为空的数据
        res.data = res.data.reduce(function (item, next) {
          obj[next.employeeId] || !next.employeeId ? '' : (obj[next.employeeId] = true && item.push(next))
          return item
        }, [])
        this.memberList = res.data
        this.fetching = false
      })
    },
    // 选择接收人
    changeEmployeeName({ guid, key, id, name, phone }) {
      this.data.map((v) => {
        if (v.guid === guid) {
          if (key == 'materialResponsibleId') {
            v.materialResponsibleId = id
            v.materialResponsibleName = name
          }
          if (key == 'tenderResponsibleId') {
            v.tenderResponsibleId = id
            v.tenderResponsibleName = name
          }
          if (key == 'brandResponsibleId') {
            v.brandResponsibleId = id
            v.brandResponsibleName = name
          }
          if (key == 'demandResponsibleId') {
            v.demandResponsibleId = id
            v.demandResponsibleName = name
          }
        }
      })
    },
    // 获取详情
    queryPlanSubSelectDetail() {
      this.$emit('update:spinning', true)
      const query = {
        planTaskDetailId: this.queryInfo.id,
        latestData: true
      }
      if (this.queryInfo.version) {
        query.latestData = false
        query.version = this.queryInfo.version
      }
      queryPlanSubSelectDetail(query)
        .then((res) => {
          if (res.data && res.data.length) {
            res.data.map((v) => (v.guid = this.getGuid()))
            this.data = res.data
          } else {
            const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
            this.data = [...DEFAULT_ROW_]
          }
          this.$emit('update:spinning', false)
        })
        .catch(() => {
          this.$emit('update:spinning', false)
        })
    },
    /**
     * @description: 递归扁平化表头并返回
     * @param {array} columns 表头
     * @param {string} parentTitle 父标题
     * @return {array}
     */
    flatColumns(columns, parentTitle = null) {
      const list = {}
      for (let i = 0; i < columns.length; i++) {
        if (columns[i]?.children || Array.isArray(columns[i].children)) {
          Object.assign(list, this.flatColumns(columns[i].children, parentTitle === null ? columns[i].title : parentTitle + '=>' + columns[i].title))
        } else {
          list[columns[i].dataIndex] = parentTitle === null ? columns[i].title : parentTitle + '=>' + columns[i].title
        }
      }
      return list
    },
    /**
     * @description: 前端解析excel导入
     * @param {Array} list 导入的列表
     * @return {void}
     */
    handleImport(list) {
      this.importLoading = true
      // 时间字段
      const timeField = ['brandLatestTime','demandLatestTime','materialLatestTime','tenderLatestTime'];
      // 时间字段和人员字段
      const timeResponField = ['responsibleTime']
      // 人员字段
      const responsibleField = ['materialResponsibleId','tenderResponsibleId','brandResponsibleId','demandResponsibleId']
      const responsibleNameField = ['materialResponsibleName','tenderResponsibleName','brandResponsibleName','demandResponsibleName']
      // 扁平化表头
      const head = this.flatColumns(this.columns.filter((el) => el.dataIndex !== 'serial' && el.dataIndex !== 'operation'))
      // excel返回数据合并后的表头字段及内容字段
      const importHead = [],
        importContent = []
      // 拆分excel返回数据表头和内容
      for (let i = 0; i < list.length; i++) {
        if (list[i].hasOwnProperty('序号')) {
          // 内容
          importContent.push(list[i])
        } else {
          // 合并后表头
          importHead.push(list[i])
        }
      }
      // 表格和导入excel表头对应
      const tableForExcel = {}
      const key = '__EMPTY_'
      // 初步获取合并表头的路径
      for (let i = 0; i < importHead.length; i++) {
        let prefix = null
        for (let el in importHead[i]) {
          if (el.indexOf(key) < 0) {
            prefix = el
          }
          if (tableForExcel.hasOwnProperty(el)) {
            tableForExcel[el] = tableForExcel[el] + '=>' + importHead[i][el]
          } else {
            tableForExcel[el] = prefix !== null ? prefix + '=>' + importHead[i][el] : importHead[i][el]
          }
        }
      }
      // 补齐合并表头的路径
      for (let item in tableForExcel) {
        if (tableForExcel[item].indexOf('=>') < 0) {
          for (let i = Number(item.split(key)[1]); i > 0; i--) {
            if (tableForExcel[key + i].indexOf('=>') > 0) {
              const arr = tableForExcel[key + i].split('=>')
              arr.pop()
              arr.push(tableForExcel[item])
              tableForExcel[item] = arr.join('=>')
              break
            }
          }
        }
      }
      // 表头对应
      for (let item in head) {
        for (let el in tableForExcel) {
          if (head[item] === tableForExcel[el]) {
            head[item] = el
          }
        }
      }
      const table = []
      // 修改字段名
      for (let i = 0; i < importContent.length; i++) {
        if (Object.keys(importContent[i]).length > 1) {
          const el = {}
          for (let item in head) {
            if (importContent[i].hasOwnProperty(head[item])) {
              el[item] = importContent[i][head[item]]
            }
          }
          // 时间字段格式化
          for(let i = 0; i < timeField.length; i++){
            if(el.hasOwnProperty(timeField[i])){
              el[timeField[i]] = this.moment(el[timeField[i]]).format('YYYY-MM-DD')
            }
          }
          // 时间和人员字段一起
          for(let i = 0; i < timeResponField.length; i++){
            if(el.hasOwnProperty(timeResponField[i])){
              if(el[timeResponField[i]] instanceof Date){  //如果传入的是Date类型就需要转化一下
                el[timeResponField[i]] = this.moment(el[timeResponField[i]]).format('YYYY-MM-DD')
              }
            }
          }
          // 人员字段匹配 responsibleField
          for(let i = 0; i < responsibleField.length; i++){
            if(el.hasOwnProperty(responsibleField[i])){
              for(let j = 0; j < this.memberList.length; j++){
                if(el[responsibleField[i]] === this.memberList[j].name){
                  el[responsibleField[i]] = this.memberList[j].userId
                  el[responsibleNameField[i]] = this.memberList[j].name
                  break
                }else if(j === this.memberList.length -1){
                  el[responsibleField[i]] = void 0
                  el[responsibleNameField[i]] = void 0
                }
              }
            }
          }
          el.guid = this.getGuid()
          table.push(el)
        }
      }
      this.data = this.data.concat(table)
      this.importLoading = false
    }
  }
}
</script>
<style lang='less' scoped>
</style>